<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>使用promise封装原生ajax</title>
</head>

<body>
    <h1>使用promise封装原生ajax</h1>
    <button id="btn1">点击我发送get请求</button>
    <button id="btn2">点击我发送post请求</button>
    <script>
        let btn1 = document.getElementById('btn1')
        let btn2 = document.getElementById('btn2')
        btn1.onclick = function () {
            sendAjax('get', 'http://localhost:3000/get', {
                m: 1,
                n: 2
            }).then(data => console.log(data)).catch(err => console.log(err))
        }
        btn2.onclick = function () {
            sendAjax('post', 'http://localhost:3000/post', {
                m: 1,
                n: 2
            }).then(data => console.log(data)).catch(err => console.log(err))
        }

        function sendAjax(method, url, data) {
            return new Promise((resolve, reject) => {
                let xhr = new XMLHttpRequest();
                xhr.onreadystatechange = function () {
                    if (xhr.readyState !== 4) {
                        return;
                    }
                    if (xhr.readyState === 4 && (xhr.status >= 200 && xhr.status < 300)) {
                        const responseObj = {
                            data: xhr.response,
                            status: xhr.status,
                            statusText: xhr.statusText
                        }
                        resolve(responseObj);
                    } else {
                        reject(new Error('请求出错了'));
                    }
                }
                let dataKeys = Object.keys(data);
                let str = dataKeys.reduce((pre, cur) => {
                    return pre += `${cur}=${data[cur]}&`
                }, '')
                str = str.substr(0, str.length - 1);
                if (method.toUpperCase() === 'GET') {
                    url += `?${str}`;
                    xhr.open(method, url);
                    xhr.send();
                } else if (method.toUpperCase() === 'POST') {
                    xhr.open(method, url);
                    xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
                    xhr.send(str);
                }
            })
        }
    </script>
</body>

</html>